package com.house.core.model;

import java.lang.reflect.Array;

/**
 *
 *
 * @author <a href="mailto:chong.sun@renren-inc.com">sun chong</a>
 * @version 2013-2-22
 */
public interface IndexEnum<E extends Enum<E>> {
	int getIndex();
	
	public static class IndexedEnumUtil{
		@SuppressWarnings("unchecked")
		public static <E extends IndexEnum> E[] toIndexe(E[] enums){
			E[] instance = (E[]) Array.newInstance(enums[0].getClass(), enums.length);
			for(E _enum : enums){
				instance[_enum.getIndex()] = _enum;
			}
			for(int i = 0; i < instance.length; i++){
				if(instance[i] == null){
					throw new IllegalStateException("The enum at index [" + i + "] has not been set.");
				}
			}
			return instance;
		}
		
		public static <E extends IndexEnum> E[] toIndexes(Class<E> clazz, E[] enums){
			E[] instance = (E[]) Array.newInstance(clazz, enums.length);
			for(E _enum : enums){
				instance[_enum.getIndex()] = _enum;
			}
			for(int i = 0; i < instance.length; i++){
				if(instance[i] == null){
					throw new IllegalStateException("The enum at index [" + i + "] has not been set.");
				}
			}
			return instance;
		}
		
		public static <E extends IndexEnum> E indexOf(final E[] enums, final int index){
			return index >= 0 && index < enums.length ? enums[index] : null;
		}
		
		public static <E extends IndexEnum> int createMask(E... es){
			int mask = 0;
			for(E e : es){
				mask |= (1 << e.getIndex());
			}
			return mask;
		}
		
		public static <E extends IndexEnum> boolean isInMask(int maskValue, E e){
			return ((maskValue >> e.getIndex()) & 1) == 1;
		}
		
		public static <E extends IndexEnum> boolean isInMask(int maskValue, int index){
			return ((maskValue >> index) & 1) == 1;
		}
	}
}
